package com.jd.tuning.jvm.objectpool.datasource;

import lombok.Data;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.sql.*;

/**
 * 连接池工厂
 */
@Data
public class ConnectionPooledObjectFactory implements PooledObjectFactory<MyConnection> {


    private ObjectPool<MyConnection> pool;


    /**
     * 包装产生连接
     * @return
     * @throws Exception
     */
    @Override
    public PooledObject<MyConnection> makeObject() throws Exception {
        //这里的配置是写死的，不够优雅
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection= DriverManager.getConnection("jdbc:mysql://10.1.4.120:3306/mybatis-faster?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8",
                "root",
                "123456");
        MyConnection myConnection=new MyConnection();
        myConnection.setConnection(connection);
        myConnection.setPool(pool);
        return new DefaultPooledObject<>(myConnection);
    }


    /**
     * 销毁连接
     * @param pooledObject
     * @throws Exception
     */
    @Override
    public void destroyObject(PooledObject<MyConnection> pooledObject) throws Exception {
        pooledObject.getObject().close();
    }


    /**
     * 校验
     * @param pooledObject
     * @return
     */
    @Override
    public boolean validateObject(PooledObject<MyConnection> pooledObject) {
        MyConnection connection= pooledObject.getObject();
        try {
            PreparedStatement preparedStatement=connection.prepareStatement("select 1");
            ResultSet resultSet=preparedStatement.executeQuery();
            int i=resultSet.getInt(1);
            return i==1;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            return false;
        }
    }

    @Override
    public void activateObject(PooledObject<MyConnection> pooledObject) throws Exception {
            //可用把MyConnection额外的配置放到这里
    }

    @Override
    public void passivateObject(PooledObject<MyConnection> pooledObject) throws Exception {
          //钝化
         MyConnection myConnection= pooledObject.getObject();
         Statement statement=myConnection.getStatement();
         if(statement!=null){
             statement.close();
         }
    }
}
